<?php
/**
 * This file is part of manage.
 * Author: tangzhou
 * Date: 2016/5/17
 * Time: 14:09
 * File: Vcc8015101601Controller.php
 */

namespace Ivr\HttpBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Elasticsearch\Client as EsClient;

/**
 * Class Vcc6017041901Controller
 * @package Ivr\HttpBundle\Controller
 */
class Vcc6017041901Controller extends Controller
{
    const MAX = 5;
    //特例号码
    public $special = array(
        95188,
    );
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function indexAction(Request $request)
    {
        $caller = $request->get('caller', '');
        $vccId = $request->get('vcc_id', '');
        if (empty($caller) || empty($vccId)) {
            $this->get("logger")->error(sprintf("caller或vccId为空,caller【%s】,vccId【%s】", $caller, $vccId));

            return new JsonResponse(array('result' => 'failure'));
        }
        //判断是否是特例号码
        if (in_array($caller, $this->special)) {
            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'code' => '200',
                ),
            ));
        };
        $startTime = strtotime(date('Y-m-d'));
        $endTime = strtotime(date('Y-m-d 23:59:59'));

        $response = array(
            'index'=>'incdr',
            'type'=>'win_incdr',
            'size'=>0, //size设置成0，这样我们就可以只看到聚合结果了,而不会显示命中的结果。
            'body' => array(
                'query' => array(
                    'bool' => array(
                        'must' => array(
                            array('match'=>array('vcc_id'=>$vccId)),
                            array('match'=>array('caller'=>$caller)),
                            array(
                                'range' => array(
                                    'start_time' => array('gte' => $startTime, 'lte' => $endTime),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
        );
        try {
            $hosts = $this->container->getParameter('elasticsearch_hosts');
            $client = new EsClient(array('hosts' => $hosts));
            $result = $client->search($response);
        } catch (\Exception $e) {
            $this->get("logger")->error($e->getMessage());

            return new JsonResponse(array('result' => 'failure'));
        }
        if ($result['hits']['total'] >= self::MAX) {
            return new JsonResponse(array('result' => 'failure'));
        }

        return new JsonResponse(array(
            'result' => 'success',
            'data' => array(
                'code' => '200',
            ),
        ));
    }
}